home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ddj0897.zip / RCSC.ZIP / LIB51 / SPRINTF.VA < prev    next >
Text File  |  1997-01-12  |  2KB  |  54 lines

  1. /*
  2. ** sprintf(buffer, ctlstring, arg, arg, ...) - Formatted print.
  3. ** Operates as described by Kernighan & Ritchie.
  4. ** b, c, d, o, s, u, and x specifications are supported.
  5. ** Note: b (binary) is a non-standard extension.
  6. */
  7. sprintf(argc) int argc; {
  8.   va_list nxtarg;
  9.   int  arg, left, pad, cc, length, maxchr, width;
  10.   char *ctl, *sptr, str[17];
  11.   char *ptr;
  12.   cc = 0;                                         
  13.   va_start(nxtarg, argc);
  14.   ptr = va_arg(nxtarg, int);
  15.   ctl = va_arg(nxtarg, int);
  16.   while(*ctl) {
  17.     if(*ctl!='%') {*ptr++ = *ctl++; ++cc; continue;}
  18.     else ++ctl;
  19.     if(*ctl=='%') {*ptr++ = *ctl++; ++cc; continue;}
  20.     if(*ctl=='-') {left = 1; ++ctl;} else left = 0;       
  21.     if(*ctl=='0') pad = '0'; else pad = ' ';           
  22.     if(isdigit(*ctl)) {
  23.       width = atoi(ctl++);
  24.       while(isdigit(*ctl)) ++ctl;
  25.       }
  26.     else width = 0;
  27.     if(*ctl=='.') {            
  28.       maxchr = atoi(++ctl);
  29.       while(isdigit(*ctl)) ++ctl;
  30.       }
  31.     else maxchr = 0;
  32.     arg = va_arg(nxtarg, int);
  33.     sptr = str;
  34.     switch(*ctl++) {
  35.       case 'c': str[0] = arg; str[1] = NULL; break;
  36.       case 's': sptr = arg;        break;
  37.       case 'd': itoa(arg,str);     break;
  38.       case 'b': itoab(arg,str,2);  break;
  39.       case 'o': itoab(arg,str,8);  break;
  40.       case 'u': itoab(arg,str,10); break;
  41.       case 'x': itoab(arg,str,16); break;
  42.       default:  *ptr = 0; return (cc);
  43.       }
  44.     length = strlen(sptr);
  45.     if(maxchr && maxchr<length) length = maxchr;
  46.     if(width>length) width = width - length; else width = 0; 
  47.     if(!left) while(width--) {*ptr++ = pad; ++cc;}
  48.     while(length--) {*ptr++ = *sptr++; ++cc; }
  49.     if(left) while(width--) {*ptr++ = pad; ++cc;}  
  50.     }
  51.   *ptr = 0;
  52.   return(cc);
  53.   }
  54.